import Store from '../database/schema/Store.js'

// const findStore = (name) => {
//   return new Promise((resolve, reject) => {
//     Store.findOne({ name }, (err, doc) => {
//         if(err){
//             reject(err);
//         }
//         resolve(doc);
//     });
//   });
// };

const findAllStore = () => {
  return new Promise((resolve, reject) => {
    Store.find({}, (err, doc) => {
      if(err){
          reject(err);
      }
      resolve(doc);
    });
  });
};

const Insert = async ( ctx ) => {
  let data = ctx.request.body
  if(!data.name){
    ctx.status = 200;
    ctx.body = {
      code: -10,
      msg: '参数不能为空',
      userMsg: '参数不能为空'
    };
    return
  }
  let store = await findAllStore()
  store = store[0]
  if(store){
    await new Promise((resolve, reject) => {
      Store.find({"name" : store.name} , function(err,docs){
        if(err){
          reject(err);
        }
        var st = docs[0]
        st.name = ctx.request.body.name                           
        st.logo = ctx.request.body.logo
        st.address = ctx.request.body.address
        st.openTime = ctx.request.body.openTime
        st.imgList = ctx.request.body.imgList
        st.notice = ctx.request.body.notice
        st.save((err) => {
          if(err){
              reject(err);
          }
          resolve();
        });
      });
    });
  }else{
    let store = new Store({
      name: ctx.request.body.name,                             
      logo: ctx.request.body.logo,
      address: ctx.request.body.address,
      openTime: ctx.request.body.openTime,
      imgList: ctx.request.body.imgList,
      notice: ctx.request.body.notice,
    });
    await new Promise((resolve, reject) => {
      store.save((err) => {
            if(err){
                reject(err);
            }
            resolve();
        });
    });
  }
  ctx.status = 200;
  ctx.body = {
    code: 0,
    msg: '保存成功',
    userMsg: '保存成功'
  }
};
const Fetch = async( ctx ) => {
  let doc = await findAllStore()
  ctx.status = 200;
  ctx.body = {
      code: 0,
      data: doc[0]
  };
};

module.exports = {
  Insert,
  Fetch
};